<template>
  <div class="login">
    <div class="loginDiv">
      <div class="leftIcon" />
      <el-form ref="loginForm" v-loading="formLoadIng" :model="loginForm" :rules="loginRules" class="login-form login-form-main">
        <div v-if="tenantCompanyInfo.logo" class="logo-base64">
          <img :src="tenantCompanyInfo.logo" :width="tenantCompanyInfo.width ? tenantCompanyInfo.width : 50" :height="tenantCompanyInfo.height ? tenantCompanyInfo.height : 50" alt="">
        </div>
        <div v-else class="logo" />
        <h3 v-if="tenantCompanyInfo.logo" class="title">{{ tenantCompanyInfo.name }}</h3>
        <h3 v-else class="title">{{ $t('J博士投资管理系统') }}</h3>
        <el-form-item prop="email">
          <el-input
            v-model="loginForm.email"
            type="text"
            auto-complete="new-password"
            clearable
            :placeholder="$t('邮箱')"
          >
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="emailCode">
          <el-input
            v-model="loginForm.emailCode"
            type="text"
            auto-complete="new-password"
            clearable
            :placeholder="$t('验证码')"
          >
            <el-button slot="append" :disabled="countDownNum !== 60" @click="getVerificationCode">
              <span v-if="countDownNum === 60">{{ $t('获取验证码') }}</span>
              <span v-if="countDownNum !== 60">{{ countDownNum }}</span>
            </el-button>
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item v-if="tenant === 'true'" prop="tenantCode">
          <el-input
            v-model="loginForm.tenantCode"
            type="text"
            auto-complete="off"
            clearable
            :placeholder="$t('机构编号')"
            @blur="getLanguage"
          >
            <svg-icon slot="prefix" icon-class="code" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item style="width:100%;">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width:100%;margin-top: 10px;"
            @keyup.enter.native="handleLogin"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">{{ $t('登 录') }}</span>
            <span v-else>{{ $t('登 录 中') }}...</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <contactUs ref="contactUs" />
  </div>
</template>

<script>
import contactUs from '@/views/contactUs'
import { getTenant, getTenantInfo } from '@/api/login'
import { getLanguage } from '@/api/dev/language/sysLanguage'
import { getVerificationCode } from '@/api/deal/indicator/data/dealIndicatorDataDetail'
export default {
  name: 'IndicatorLogin',
  components: {
    contactUs
  },
  data() {
    const checkEmail = (rule, value, callback) => {
      if (value === '' || value === undefined || value === null) {
        callback(new Error(this.$t('请正确填写邮箱')))
      } else {
        const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
        if (!reg.test(value)) {
          callback(new Error(this.$t('请输入有效的邮箱')))
        } else {
          callback()
        }
      }
    }
    return {
      codeUrl: '',
      cookiePassword: '',
      // 是否多租户模式
      tenant: 'false',
      // 等待框
      formLoadIng: false,
      loginForm: {
        dataId: undefined,
        email: '',
        emailCode: '',
        tenantCode: this.$route.query.tenantCode,
        uuid: ''
      },
      rememberMe: true,
      loginRules: {
        email: [
          { required: true, trigger: 'blur', validator: checkEmail }
        ],
        // emailCode: [
        //   { required: true, trigger: 'blur', message: this.$t('必填信息') }
        // ],
        tenantCode: [
          { required: true, trigger: 'blur', message: this.$t('必填信息') }
        ]
      },
      loading: false,
      // 倒计时
      countDownNum: 60,
      tenantCompanyInfo: {
        logo: undefined,
        name: undefined,
        width: undefined,
        height: undefined
      }
    }
  },
  watch: {
  },
  created() {
    // 退出登录
    this.$store.dispatch('LogOut')
    // 查询是否多租户
    this.getTenant()
    // 获取租户logo和名称
    this.getTenantInfo()
  },
  mounted() {
    // 绑定登录页回车键登录事件
    window.addEventListener('keydown', this.keyDown)
  },
  // 增加登录页回车键登录功能
  methods: {
    keyDown(e) {
      if (e.keyCode === 13) {
        this.handleLogin()
      }
    },
    /**
     * 获取是不是多租户模式
     */
    getTenant() {
      this.formLoadIng = true
      getTenant().then(res => {
        if (res !== undefined) {
          this.tenant = res.data
        }
      })
    },
    // 获取当前租户的logo和名称
    getTenantInfo(tenantCode) {
      // 从url中获取租户code
      if (tenantCode === undefined) {
        tenantCode = this.$route.query.tenantCode
      }
      if (tenantCode !== undefined) {
        this.loginForm.tenantCode = tenantCode
      }
      if (this.$route.query.email !== undefined) {
        this.loginForm.email = this.$route.query.email
      }
      getTenantInfo(this.loginForm.tenantCode).then(res => {
        if (res.data !== null) {
          this.tenantCompanyInfo.logo = res.data.productLogo
          this.tenantCompanyInfo.name = res.data.productName
          this.tenantCompanyInfo.width = res.data.productLogoWidth
          this.tenantCompanyInfo.height = res.data.productLogoHeight
        } else {
          this.tenantCompanyInfo = { logo: undefined, name: undefined, width: undefined, height: undefined }
        }
        console.log(JSON.stringify(this.tenantCompanyInfo))
        window.localStorage.setItem('tenantCompanyInfo', JSON.stringify(this.tenantCompanyInfo))
        this.formLoadIng = false
      }).catch(() => {
        this.tenantCompanyInfo = { logo: undefined, name: undefined, width: undefined, height: undefined }
        this.formLoadIng = false
      })
    },
    getLanguage() {
      getLanguage(undefined, this.loginForm.tenantCode).then(response => {
        var localStorage = window.localStorage.getItem('language')
        if (localStorage === undefined || localStorage === null || localStorage === 'null') {
          localStorage = 'zh_cn'
        }
        this.$i18n.vm.messages[localStorage] = response.languageData
        // 修改国际化词条
        window.localStorage.setItem('language_' + localStorage, JSON.stringify(response.languageData))
        window.localStorage.setItem('language', localStorage)
        this.$i18n.locale = localStorage
      })
      this.getTenantInfo(this.loginForm.tenantCode)
    },
    /**
     * 获取验证码
     */
    getVerificationCode() {
      this.$refs.loginForm.validate(valid => {
        const flag = (this.loginForm.emailCode === undefined || this.loginForm.emailCode === null || this.loginForm.emailCode === '')
        if (valid || flag) {
          this.msgSuccess(this.$t('发送至您的邮箱,请注意查收!'))
          const timeout = setInterval(() => {
            this.countDownNum--
            if (this.countDownNum <= 0) {
              this.countDownNum = 60
              clearInterval(timeout)
            }
          }, 1000)
          console.log(this.loginForm.email, this.loginForm.tenantCode)
          getVerificationCode(this.loginForm.email, this.loginForm.tenantCode).then(response => {
            console.log(response)
          }).catch(() => {
            this.msgError(this.$t('发送邮箱时发生异常, 请检查您的邮箱或联系管理员!'))
          })
        }
      })
    },
    handleLogin() {
      console.log('登录')
      var _this = this
      _this.$refs.loginForm.validate(valid => {
        if (valid) {
          _this.loading = true
          _this.loginForm.dataId = _this.$route.query.id
          _this.$store.dispatch('IndicatorLogin', _this.loginForm).then(() => {
            _this.$router.push({
              path: '/dealIndicatorDataMainPublic',
              query: {
                id: _this.$route.query.id,
                cacheId: _this.$route.query.cacheId
              }
            })
          })
          .catch((err) => {
            _this.loading = false
            console.error(err)
          })
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.pub-icon{
  position: fixed;
  right: 20px;
  top: 20px;
  display: flex;
  align-items: center;
  font-weight: bold;
  background-image: linear-gradient(0deg, #04c5dc, #069cf3);
  -webkit-background-clip:text;
  color: transparent;
  .pub{
    display: inline-block;
    width: 25px;
    height: 25px;
    background-size: cover;
    background-image: url();
  }
}
.login .el-login-footer{
  height: unset!important;
  line-height: unset!important;
  bottom: 5px!important;
  .links{
    margin: 0 0 5px;
    a{
      text-decoration: underline;
    }
  }
}
</style>
